<script lang="ts" setup>
import type { DataTableColumns } from 'naive-ui';
import { NButton, NSpace } from 'naive-ui';
import { h, onBeforeMount, ref } from 'vue';
import type { RowData } from 'naive-ui/es/data-table/src/interface';
import { longDateTimeRender } from '~/src/utils/view';
import { isEmpty } from '@/utils/string';
import { isSuccess } from '@/utils/response';
import * as service from './modules/api';
import CreateModule from './modules/create-module.vue';
import EditModule from './modules/edit-module.vue';
import DeleteModule from './modules/delete-module.vue';

const loading = ref<boolean>(false);
const listData = ref<any>([]);

const defaultSearchForm = {
  name: ''
};
const searchForm = ref({ ...defaultSearchForm });

const columns: DataTableColumns = [
  { title: '名称', key: 'name', width: 200 },
  { title: 'ID', key: 'id', width: 265 },
  {
    title: '创建时间',
    key: 'createTime',
    render: longDateTimeRender('createTime')
  },
  {
    title: '更新时间',
    key: 'updateTime',
    render: longDateTimeRender('updateTime')
  },
  {
    title: '操作',
    key: 'edit',
    fixed: 'right',
    width: 200,
    render: row => {
      return h(NSpace, {}, () => [
        h(
          EditModule,
          {
            id: () => row.id,
            callback: () => {
              list();
            }
          },
          () => '编辑'
        ),
        h(
          DeleteModule,
          {
            id: () => row.id,
            callback: () => {
              list();
            }
          },
          () => '删除'
        )
      ]);
    }
  }
];

async function list() {
  let response;
  if (isEmpty(searchForm.value.name)) {
    response = await service.tree({ include: false });
  } else {
    response = await service.list(searchForm.value);
  }
  if (isSuccess(response)) {
    listData.value = response.data;
  }
}

function reset() {
  searchForm.value = { ...defaultSearchForm };
  list();
}

onBeforeMount(async () => {
  list();
});
</script>

<template>
  <NSpace vertical size="large">
    <n-form inline :label-width="80" :model="searchForm">
      <n-form-item label="菜单名:" path="searchForm.name">
        <n-input v-model:value="searchForm.name" type="text"></n-input>
      </n-form-item>
      <n-form-item>
        <NButton @click="list()">查询</NButton>
        <NButton @click="reset()">重置</NButton>
      </n-form-item>
      <n-form-item>
        <CreateModule :callback="() => list()"></CreateModule>
      </n-form-item>
    </n-form>
    <n-data-table
      remote
      bordered
      :single-line="false"
      :loading="loading"
      :data="listData"
      :row-key="(row: RowData) => row.id"
      :columns="columns"
      :scroll-x="1800"
    ></n-data-table>
  </NSpace>
</template>

<style scoped>
.n-button {
  margin-left: 10px;
}
</style>
